<!DOCTYPE HTML>
<html>
<head>
    <title>My WebSocket</title>
</head>

<body>
server地址 :  <input id ="serveraddress" type="text" /><br/>
您的用户id :  <input id ="userId" type="text" /><br/>
<button onclick="initSocket()">连接</button><br/>

=====================================================<br/>
消息 :  <input id ="message" type="text" /><br/>
<button onclick="send()">发送</button><br/>
=====================================================<br/>
连接状态 : <button onclick="clearConnectStatu()">清空</button><br/>
<div id="connectStatu"></div><br/>

=====================================================<br/>
收到消息 :<br/>
<div id="receivedMessage"></div><br/>
=====================================================<br/>
心跳 :<br/>
<div id="heartdiv"></div><br/>

</body>

<script src="./js/jquery.min.js"></script>
<script type="text/javascript">
    var heartflag = false;
    var webSocket = null;
    var tryTime = 0;
    $(function () {
//        initSocket();
        window.onbeforeunload = function () {

        };
    });

    /**
     * 初始化websocket，建立连接
     */
    function initSocket() {
        var serveraddress = $("#serveraddress").val();
        var userId = $("#userId").val();

        if (!window.WebSocket) {
            $("#connectStatu").append(getNowFormatDate()+"  您的浏览器不支持ws<br/>");
            return false;
        }

        webSocket = new WebSocket(serveraddress+"/"+userId);

        // 收到服务端消息
        webSocket.onmessage = function (msg) {
            if(msg.data == "&"){
<!--                $("#heartdiv").append(getNowFormatDate()+"  心跳 <br/>");-->
            }else{
                $("#receivedMessage").append(getNowFormatDate()+"  收到消息 : "+msg.data+"<br/>");
            }
        };

        // 异常
        webSocket.onerror = function (event) {
            heartflag = false;
<!--            $("#connectStatu").append(getNowFormatDate()+"  异常<br/>");-->
        };

        // 建立连接
        webSocket.onopen = function (event) {
            heartflag = true;
            heart();
            $("#connectStatu").append(getNowFormatDate()+"  建立连接成功<br/>");
            tryTime = 0;
        };

        // 断线重连
        webSocket.onclose = function () {
            heartflag = false;
            // 重试10次，每次之间间隔10秒
            if (tryTime < 10) {
                setTimeout(function () {
                    webSocket = null;
                    tryTime++;
                    initSocket();
                    $("#connectStatu").append( getNowFormatDate()+"  第"+tryTime+"次重连<br/>");
                }, 3*1000);
            } else {
                alert("重连失败.");
            }
        };

    }

    function send(){
        var message = $("#message").val();
        webSocket.send(message);
    }

    function clearConnectStatu(){
        $("#connectStatu").empty();
        $("#receivedMessage").empty();
        $("#heartdiv").empty();
    }

    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var sp3 = ".";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                + " " + date.getHours() + seperator2 + date.getMinutes()
                + seperator2 + date.getSeconds() + sp3 + date.getMilliseconds();
        return currentdate;
    }

    function heart() {
        if (heartflag){
            webSocket.send("&");
            $("#heartdiv").append(getNowFormatDate()+"  心跳 <br/>");
        }
<!--        setTimeout("heart()", 10*1000);-->

    }
</script>


</html>